<template>
  <el-dialog
    :model-value="visible"
    @update:model-value="$emit('update:visible', $event)"
    title="新增业主"
    width="1000px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      label-position="right"
    >
      <!-- 房户选择区域 -->
      <el-card class="household-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span class="card-title">房户选择</span>
            <span class="card-subtitle">请选择业主关联的房户</span>
          </div>
        </template>
        <HouseholdSelector
          v-model="householdSelector"
          @change="handleHouseholdChange"
        />
      </el-card>

      <!-- 业主信息区域 -->
      <el-card class="owner-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span class="card-title">业主信息</span>
            <span class="card-subtitle">请填写业主基本信息</span>
          </div>
        </template>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="业主姓名" prop="ownerName">
              <el-input
                v-model="formData.ownerName"
                placeholder="请输入业主姓名"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证号" prop="idCard">
              <el-input
                v-model="formData.idCard"
                placeholder="请输入身份证号"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input
                v-model="formData.phone"
                placeholder="请输入联系电话"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱地址" prop="email">
              <el-input
                v-model="formData.email"
                placeholder="请输入邮箱地址"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="formData.gender" placeholder="请选择性别" clearable style="width: 100%">
                <el-option label="男" :value="1" />
                <el-option label="女" :value="2" />
                <el-option label="未知" :value="0" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出生日期" prop="birthDate">
              <el-date-picker
                v-model="formData.birthDate"
                type="date"
                placeholder="请选择出生日期"
                style="width: 100%"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="职业" prop="occupation">
              <el-input
                v-model="formData.occupation"
                placeholder="请输入职业"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工作单位" prop="company">
              <el-input
                v-model="formData.company"
                placeholder="请输入工作单位"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="联系地址" prop="address">
              <el-input
                v-model="formData.address"
                placeholder="请输入联系地址"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="紧急联系人" prop="emergencyContact">
              <el-input
                v-model="formData.emergencyContact"
                placeholder="请输入紧急联系人"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="紧急联系电话" prop="emergencyPhone">
              <el-input
                v-model="formData.emergencyPhone"
                placeholder="请输入紧急联系电话"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注信息" prop="remark">
              <el-input
                v-model="formData.remark"
                type="textarea"
                :rows="3"
                placeholder="请输入备注信息"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { ownerApi, type OwnerDTO, type OwnerWithHouseholdDTO } from '@/api/owner'
import HouseholdSelector from './HouseholdSelector.vue'

// 定义组件属性
interface Props {
  visible: boolean
}

// 定义组件事件
interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 表单引用
const formRef = ref<FormInstance>()

// 提交加载状态
const submitLoading = ref(false)

// 房户选择器数据
const householdSelector = reactive({
  communityId: undefined as number | undefined,
  buildingId: undefined as number | undefined,
  unitId: undefined as number | undefined,
  householdId: undefined as number | undefined
})

// 表单数据
const formData = reactive<OwnerDTO & { householdId?: number }>({
  ownerName: '',
  idCard: '',
  phone: '',
  email: undefined,
  gender: undefined,
  birthDate: undefined,
  address: undefined,
  occupation: undefined,
  company: undefined,
  emergencyContact: undefined,
  emergencyPhone: undefined,
  remark: undefined,
  status: 1,
  householdId: undefined
})

// 表单验证规则
const formRules: FormRules = {
  ownerName: [
    { required: true, message: '请输入业主姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '业主姓名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  idCard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, message: '请输入正确的身份证号', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  householdId: [
    { required: true, message: '请选择房户', trigger: 'change' }
  ]
}

// 监听房户选择变化
const handleHouseholdChange = (value: any) => {
  console.log('房户选择变化:', value)
  // 同步房户ID到表单数据，用于验证
  formData.householdId = value.householdId
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) {
    return
  }
  
  try {
    // 验证表单
    await formRef.value.validate()
    
    // 验证房户选择 - 使用表单验证规则，不需要额外验证
    // if (!householdSelector.householdId) {
    //   ElMessage.error('请选择房户')
    //   return
    // }
    
    submitLoading.value = true
    
    // 构建提交数据
    const submitData: OwnerWithHouseholdDTO = {
      ownerInfo: { ...formData },
      householdId: formData.householdId || householdSelector.householdId
    }
    
    // 调用API
    const response = await ownerApi.addOwnerWithHousehold(submitData)
    
    if (response.code === 200) {
      ElMessage.success('新增业主成功')
      emit('success')
      handleCancel()
    } else {
      ElMessage.error(response.message || '新增业主失败')
    }
  } catch (error) {
    console.error('新增业主失败:', error)
    ElMessage.error('新增业主失败')
  } finally {
    submitLoading.value = false
  }
}

// 取消操作
const handleCancel = () => {
  // 重置表单
  if (formRef.value) {
    formRef.value.resetFields()
  }
  
  // 重置房户选择器
  if (householdSelector) {
    householdSelector.communityId = undefined
    householdSelector.buildingId = undefined
    householdSelector.unitId = undefined
    householdSelector.householdId = undefined
  }
  
  // 重置表单数据
  Object.assign(formData, {
    ownerName: '',
    idCard: '',
    phone: '',
    email: undefined,
    gender: undefined,
    birthDate: undefined,
    address: undefined,
    occupation: undefined,
    company: undefined,
    emergencyContact: undefined,
    emergencyPhone: undefined,
    remark: undefined,
    status: 1
  })
  
  emit('update:visible', false)
}

// 监听对话框显示状态，重置表单
watch(() => props.visible, (newVal) => {
  if (!newVal) {
    handleCancel()
  }
})
</script>

<style lang="scss" scoped>
.household-card,
.owner-card {
  margin-bottom: 20px;
  
  .card-header {
    display: flex;
    align-items: center;
    
    .card-title {
      font-size: 16px;
      font-weight: 600;
      color: #303133;
      margin-right: 8px;
    }
    
    .card-subtitle {
      font-size: 12px;
      color: #909399;
    }
  }
}

.dialog-footer {
  text-align: right;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-input),
:deep(.el-select),
:deep(.el-date-picker) {
  width: 100%;
}
</style>
